package com.sqm.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import com.sqm.config.BaseContext;
import com.sqm.entity.User;
import com.sqm.exception.ServiceException;
import com.sqm.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 功能: 校验token，jwt令牌
 * 作者: 沙琪马
 * 日期: 2024/5/21 18:25
 */
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token"); // 从前端获取token
        if (StrUtil.isBlank(token)){
            token = request.getParameter("token"); // url参数 ?token=xxxx
        }

        // 通过注解的方式通过放行
        if(handler instanceof HandlerMethod) {
            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (annotation != null) {
                return true;
            }
        }

        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401","请登录");
        }
        // 获取token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0); // JWT.decode(token) 解码JWT token
            BaseContext.setCurrentId(Integer.valueOf(userId));
        } catch (JWTDecodeException j){
            throw new ServiceException("401", "请登录");
        }

        // 根据token中的userId查询数据库
        User user = userMapper.selectById(Integer.valueOf(userId));
        if (user == null) {
            throw new ServiceException("401", "请登录");
        }

        // 通过用户密码加密之后生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e){
            throw new ServiceException("401", "请登录");
        }

        return true;
    }
}
